var Calendar = {
	calendar: null,
	targetElement: null,
	selfElement: null,
	currDate: [],
	dataRange: ['2011-11-01','2011-11-09'],
	firstDay: 1,
	cfgDate: [],
	//first day of week. 1: Monday is the first day; 0: Sunday is the first day
	format: "YYYY-MM-DD",
	createBody: function() {
		if (this.calendar == null) {
			var oDiv = W('.ID-datecontrol-calendar')[0];
			return oDiv;
		}
		return this.calendar;
	},

	createDateTable: function(dte,num) {
		//var ArrWeek = new Array('日', '一', '二', '三', '四', '五', '六');
		var ArrWeek  = ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"];
		//var ArrWeek = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
		var year = dte.getFullYear();
		var month = dte.getMonth();
		var date = this.currDate[num].getDate();
		var fromDate = -(new Date(year, month, 1).getDay() + 7 - this.firstDay) % 7 + 1;
		var today = window.systemDate || new Date();
		var rangeStart = this.isDate(this.dataRange[0]);
		var rangeEnd = this.isDate(this.dataRange[1]);
		console.log(rangeStart);
		console.log(rangeEnd);

		var htmlHd = ['<tr><th class="qwrap-date-picker-select qwrap-date-picker-select-month C_DATEPICKER_SELECT_IN_RANGE">月</th>'],
			str_wk='',
			htmlBd=[],
			str_day='';

		for(var i=0,len=7; i<len; i++){
			htmlHd.push('<th class="qwrap-date-picker-wday">'+ArrWeek[(i + this.firstDay) % 7]+'</th>');
		}
		htmlHd.push('</tr>');

		for(var i=0,len=42; i<len; i++){
			var d = new Date(year, month, fromDate + i);
			var id = i + num*42;
			//if (i % 7 == 0) html.push('<tr>');
			var status = 0;//普通日期
			if (d.getMonth() == this.cfgDate[num].getMonth() && d.getDate() == this.cfgDate[num].getDate()) {
				//来源时间
				status = 3;
			}
			if (d.getMonth() == today.getMonth() && d.getDate() == today.getDate()) {
				//today
				status = 2;
			}
			if (d.getDay() == 0){
				//sunday
				status = 4;
			}
			if (d.getDay() == 6) {
				//saturday
				status = 5;
			}
			if (d.getMonth() != month){
				status = 1;//不在本月
			}
			if (i % 7 == 0) htmlBd.push('<tr><th class="qwrap-date-picker-select">周</th>');
			//区间状态:C_DATEPICKER_DATE_DISABLED C_DATEPICKER_NO_RANGE C_DATEPICKER_IN_RANGE
			if(status !== 1){
				if(d > today){
					var rangeStatus = 'C_DATEPICKER_DATE_DISABLED';
				}else{
					if(d >= rangeStart && d <= rangeEnd){
						var rangeStatus = 'C_DATEPICKER_IN_RANGE';
					}else{
						var rangeStatus = 'C_DATEPICKER_NO_RANGE';
					}
				}
				htmlBd.push('<td data-id="'+id+'" class="qwrap-date-picker-date s' + status + ' '+ rangeStatus +'" data-value="'+this.formatDate(d, this.format)+'">'+d.getDate()+'</td>');
				
			}else{
				htmlBd.push('<td data-id="'+id+'" class="qwrap-date-picker-date s'+status+'"></td>');
			}
			if (i % 7 == 6) htmlBd.push('</tr>');
		}
		str_wk = htmlHd.join('');
		str_day = htmlBd.join('');
		W('.ID-date-picker-bd')[num].innerHTML = str_wk + str_day;
		return str_wk + str_day;
	},
	create: function() {
		var el_datepicker = W('.ID-datepicker',this.calendar);
		el_datepicker.html('');
		console.log(this.currDate);
		var tpl_datepicker_hd = '<td width="50%" class="ID-select-year qwrap-date-picker-year">{$year}\
<div class="qwrap-date-picker-select-btn">\
<span class="qwrap-date-picker-select-btn-pre G_CLICK" onclick="Calendar.nextMonth(-12,{$num})" title="pre Year"></span>\
<span class="qwrap-date-picker-select-btn-next G_CLICK" onclick="Calendar.nextMonth(12,{$num})" title="next Year"></span>\
</div></td>\
<td  class="ID-select-month qwrap-date-picker-month">{$month}\
<div class="qwrap-date-picker-select-btn">\
<span class="qwrap-date-picker-select-btn-pre G_CLICK" onclick="Calendar.nextMonth(-1,{$num})" title="pre Month">&lt;</span>\
<span class="qwrap-date-picker-select-btn-next G_CLICK"  onclick="Calendar.nextMonth(1,{$num})" title="next Month">&gt;</span>\
			</div></td>';

		var Mon_Left = tpl_datepicker_hd.tmpl({'year':this.formatDate(this.currDate[0], "YYYY"),'month':this.formatDate(this.currDate[0], "OO"),'num':0});
		var Mon_Right = tpl_datepicker_hd.tmpl({'year':this.formatDate(this.currDate[1], "YYYY"),'month':this.formatDate(this.currDate[1], "OO"),'num':1});

		W('.ID-date-picker-hd')[0].innerHTML = Mon_Left;
		W('.ID-date-picker-hd')[1].innerHTML = Mon_Right;

		var calLeft = this.createDateTable(this.currDate[0],0);
		var calRight = this.createDateTable(this.currDate[1],1);
	},
	Bind: function(evt, config) {
		this.selfElement = evt.target ? evt.target: evt.srcElement;
		
		if (typeof(config) != 'undefined') {
			this.targetElement = typeof(config.target) == 'undefined' ? this.selfElement: config.target;
			this.format = typeof(config.format) == 'undefined' ? this.format: config.format;
		} else {
			this.format = "YYYY-MM-DD";
			this.targetElement = this.selfElement;
		}
		
		this.calendar = this.createBody();
		//当前日期
		var defDate = this.isDate(document.getElementById(this.targetElement).value);
		this.cfgDate[1] = defDate ? defDate: new Date();
		this.cfgDate[0] = new Date(this.cfgDate[1].getFullYear(),this.cfgDate[1].getMonth()-1,this.cfgDate[1].getDate());
		this.currDate[1] = this.cfgDate[1];
		this.currDate[0] =  this.cfgDate[0];
		this.show();
	},
	show: function() {
		var self = this;
		W('.ID-datecontrol-pickers').delegate('td','click',function(e){
			var val = W(this).attr('data-value');
			if(val === null || W(this).hasClass('C_DATEPICKER_DATE_DISABLED')){
				return;
			}
			if(self.dataRange.length === 2){
				self.dataRange = [val];
				W('.C_DATEPICKER_IN_RANGE',this).replaceClass('C_DATEPICKER_IN_RANGE','C_DATEPICKER_NO_RANGE');
				
			}else{
				self.dataRange.push(val);
			}
			self.create();
			self.updateInput();
			self.updateSelect();
		});
		var w_input = W('.ID-datecontrol-primary-custom input');
		w_input.on('focus',function(e){
			w_input.removeClass('C_DATECONTROL_PICK');
			W(this).addClass('C_DATECONTROL_PICK');
		});
		w_input.on('blur',function(){
			var val = W(this).val().trim();
			var val0 = w_input[0].value.trim();
			var val1 = w_input[1].value.trim();
			var date_val = self.isDate(val);
			var date_val0 = self.isDate(val0);
			var date_val1 = self.isDate(val1);

			var el_apply = W('.ID-apply')[0];
			var w_this = W(this);
			el_apply.disabled = false;
			//check format
			if(!date_val){
				w_this.addClass('C_DATECONTROL_ERROR');
				el_apply.disabled = true;
				alert('1日期格式错误了!');
				this.focus();
				return false;
			}
			if(!date_val0 || !date_val1){
				alert('2日期格式错误了!');
				this.focus();
				el_apply.disabled = true;
				return false;
			}
			//check range
			if(date_val0 > date_val1){
				console.log('check range err');
				w_this.addClass('C_DATECONTROL_ERROR');
				el_apply.disabled = true;
				alert('3区间错误了!');
				this.focus();
				return false;
			}else{
				w_input.removeClass('C_DATECONTROL_ERROR');
				el_apply.disabled = false;
			}
			self.dataRange = [val0,val1];
			
			if(date_val0.getMonth() == date_val1.getMonth() && date_val0.getFullYear() == date_val1.getFullYear()){
				date_val0.setMonth(date_val0.getMonth() -1);
			}
			self.currDate = [date_val0,date_val1];
			console.log(self.dataRange);
			console.log(self.currDate);
			self.create();
			self.updateSelect();
		});

		this.create();
		this.updateInput();
		this.updateSelect();
		var Rect = this.getPosition(this.selfElement);
		this.calendar.style.left = (Rect.L) + "px";
		this.calendar.style.top = (Rect.T + Rect.H) + "px";
		this.calendar.style.display = '';
	},
	hidden: function() {
		this.calendar.style.display = 'none';
	},
	updateInput: function(){
		if(this.dataRange.length === 2){
			W('.ID-datecontrol-primary-start').val(this.dataRange[0]).removeClass('C_DATECONTROL_PICK');
			W('.ID-datecontrol-primary-end').val(this.dataRange[1]).addClass('C_DATECONTROL_PICK');
		}else{
			W('.ID-datecontrol-primary-start').val(this.dataRange[0]).addClass('C_DATECONTROL_PICK');
			W('.ID-datecontrol-primary-end').val(this.dataRange[0]).removeClass('C_DATECONTROL_PICK');
		}
	},
	updateSelect: function(){
	    console.log('updateSelect=========');
	    console.log(this.dataRange);
	    if(this.dataRange.length !== 2){
	        return false;
	    }
		var s_day = this.isDate(this.dataRange[0]);
		var e_day = this.isDate(this.dataRange[1]);
		var l_day = this.currDate[0];
		var r_day = this.currDate[1];
		
		var isfullyear0 = s_day.getTime() == new Date(l_day.getFullYear(),1,1).getTime() && e_day.getFullYear().getTime() >= new Date(l_day.getFullYear(),12,31).getTime();
		
		var isfullyear1 = e_day.getTime() == new Date(r_day.getFullYear(),12,31).getTime() && s_day.getTime() <= new Date(r_day.getFullYear(),1,1).getTime();
		
		var s_day2 = new Date(l_day.getFullYear(),1,1);
        s_day2.setMonth(l_day.getMonth()+1);
        s_day2.setDate(0);
        
        var e_day2 = new Date(r_day.getFullYear(),1,1);
        e_day2.setMonth(r_day.getMonth()+1);
        e_day2.setDate(0);
        
		var isfullmonth0 = s_day.getTime() == new Date(l_day.getFullYear(),l_day.getMonth(),1).getTime() && e_day.getTime() >= s_day2.getTime();
		var isfullmonth1 = s_day.getTime() <= new Date(r_day.getFullYear(),r_day.getMonth(),1).getTime() && e_day.getTime() == e_day2.getTime();
		
		console.log(e_day.getTime()  +'=='+ e_day2.getTime());
		console.log(isfullmonth0);
		console.log(isfullmonth1);
		
	    var el_fullmonth0 =  W('.qwrap-date-picker-select-month')[0];
	    var el_fullmonth1 =  W('.qwrap-date-picker-select-month')[1];
	    var el_month_lab0 = W('.ID-select-month')[0];
	    var el_month_lab1 = W('.ID-select-month')[1];
	    var el_year_lab0 = W('.ID-select-year')[0];
	    var el_year_lab1 = W('.ID-select-year')[1];
	    
	    if(isfullyear0){
	        W(el_year_lab0).addClass('C_DATEPICKER_IN_RANGE');
	    }
	    if(isfullyear1){
	        W(el_year_lab1).addClass('C_DATEPICKER_IN_RANGE');
	    }
	    if(isfullmonth0){
	        W(el_month_lab0).addClass('C_DATEPICKER_IN_RANGE');
	    }
	    if(isfullmonth1){
	        W(el_month_lab1).addClass('C_DATEPICKER_IN_RANGE');
	    }
	},
	nextMonth: function(val,num) {
		var valAbs = Math.abs(val);
		var num2 = Math.abs(num-1);
		var year = this.currDate[0].getFullYear();
		var month = this.currDate[0].getMonth();
		var date = this.currDate[0].getDate();
		var newCurrDate0 = new Date(year, month + valAbs, date);
		var isbind = false;
		//左侧日期加上移动值大于等于右侧，则存在联动关系
		if(newCurrDate0 >= this.currDate[1]){
			if(num === 0){
				if(val > 0){
					isbind = true;
				}
			}else{
				if(val < 0){
					isbind = true;
				}
			}
		}
		console.log(isbind);
		var _currDate = [],
			d = new Date();
		var today = d.setDate(date);
		_currDate[num] = new Date(this.currDate[num].getFullYear(), this.currDate[num].getMonth() + val, this.currDate[num].getDate()),
		_currDate[num2] = new Date(this.currDate[num2].getFullYear(), this.currDate[num2].getMonth() + val, this.currDate[num2].getDate());

		//新日期不能大于今天
		if(_currDate[1] > today || _currDate[num2] > today){
			return;
		}
		this.currDate[num] = _currDate[num];
		if(isbind){
			this.currDate[num2] = _currDate[num2];
		}
		this.create();
	},
	setValue: function(val) {
		this.targetElement.value = val;
		this.hidden();
	},
	formatDate: function(date, str) { //格式化日期
		//var MonName = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
		var MonName = ["\u4E00\u6708", "\u4E8C\u6708", "\u4E09\u6708", "\u56DB\u6708", "\u4E94\u6708", "\u516D\u6708", "\u4E03\u6708", "\u516B\u6708", "\u4E5D\u6708", "\u5341\u6708", "\u5341\u4E00\u6708", "\u5341\u4E8C\u6708"];
		var sMon = date.getMonth() + 1;
		sMon = (sMon > 9) ? sMon.toString() : ("0" + sMon.toString());
		var sDay = date.getDate();
		sDay = (sDay > 9) ? sDay.toString() : ("0" + sDay.toString());
		var sYear = date.getYear();
		sYear = (sYear > 9) ? sYear.toString() : ("0" + sYear.toString());

		str = str.replace("YYYY", date.getFullYear());
		str = str.replace("MM", sMon);
		str = str.replace("DD", sDay);
		str = str.replace("YY", sYear);
		str = str.replace("M", date.getMonth() + 1);
		str = str.replace("D", date.getDate());
		str = str.replace("OO", MonName[date.getMonth()]);
		return str;
	},
	isDate: function(str) { //判断是否日期()
		if (str == null) return false;
		var exp = /^(\d{1,4})(-|\/|\.)(\d{1,2})\2(\d{1,2})$/;
		var r = str.match(exp);
		if (r == null) return false;
		var d = new Date(r[1], r[3] - 1, r[4]);

		var flg = (d.getFullYear() == parseInt(r[1], 10) && (d.getMonth() + 1) == parseInt(r[3], 10) && d.getDate() == parseInt(r[4], 10))

		return flg ? d: false;
	},
	isMonthEquals: function(date1, date2) { ///是否同一个月
		return date1.getMonth() == date2.getMonth() && date1.getFullYear() == date2.getFullYear();
	},
	isDayEquals: function(date1, date2) { ///是否同一天
		return this.isMonthEquals(date1, date2) && date1.getDate() == date2.getDate();
	},
	getPosition: function(obj) {
		var WW = obj.offsetWidth;
		var HH = obj.offsetHeight;

		var TT = 0;
		var LL = 0;
		do {
		  TT += obj.offsetTop;
		  LL += obj.offsetLeft;
		  obj = obj.offsetParent;
		} while ( obj != window . document . body ) return {
		  L: LL,
		  T: TT,
		  H: HH,
		  W: WW
		};
	}
};